import type { NextFunction, Response, Request } from "express";
import AppError from "../class/AppError.js"

const sendErrorDev = (err: AppError, req: Request, res: Response) => {
  res.status(err.statusCode).json({
    status: err.status,
    error: err,
    message: err.message,
    stack: err.stack
  });
};
const sendErrorProd = (err: AppError, req: Request, res: Response) => {
  if (err.isOperation) {
    // 操作错误, trusted error
    res.status(err.statusCode).json({
      status: err.status,
      message: err.message
    });
  } else {
    // 编程或其它错误：unknown error
    // 1 Log error
    console.error('ERROR ✨', err);
    // 2 Send generic message
    res.status(500).json({
      status: 'error',
      message: 'Something went very wrong!'
    });
  }
};

export default function (err: AppError, req: Request, res: Response, next: NextFunction) {
  err.statusCode = err.statusCode || 500;
  err.status = err.status || 'error';

  if (process.env.NODE_ENV === 'development') {
    sendErrorDev(err, req, res);
  }
  else if (process.env.NODE_ENV === 'production') {
    sendErrorProd(err, req, res);
  }
};
